import { defineComponent, reactive } from 'vue'
import SearchInput from '@/components/SearchInput'
import { useRoute, useRouter } from 'vue-router'
import { SearchShop } from '@/types/model'
import { searchShopApi } from '@/api/search'
import { useSearchEffect } from '@/hooks/useSearch'

interface SearchResultData {
  list: SearchShop[]
}

/* 搜索结果列表 */
const useShopListEffect = () => {
  const data: SearchResultData = reactive({
    list: []
  })

  const searchShop = async (keyword: string) => {
    const res = await searchShopApi({ keyword })
    if (res.code === 0) {
      data.list = res.data
    }
  }

  return {
    data,
    searchShop
  }
}

export default defineComponent({
  name: 'SearchResult',
  setup () {
    const route = useRoute()
    const router = useRouter()
    const { data, searchShop } = useShopListEffect()
    const { searchText, search } = useSearchEffect()
    searchText.value = route.query.search as string
    searchShop(searchText.value)
    /* render 函数 */
    return () => {
      const shopList = data.list.map(shop => {
        const productList = shop.products.map(product => (
          <div class="search__product">
            <img src={ product.imgUrl } />
            <div class="name">{ product.name }</div>
            <div class="price">
              <span class="yen">￥</span>
              <span class="now">{ product.price }</span>
              <span class="price__old">{ product.oldPrice }</span>
            </div>
          </div>
        ))
        return (
          <div class="search__shop" onClick={ () => { router.push(`/shop/${shop.id}`) } }>
            <img src={ shop.imgUrl } />
            <div class="content">
              <div class="title">{ shop.title }</div>
              <div class="tags">
                <span class="tag">月售{ shop.sales }+</span>
                <span class="tag">起送¥{ shop.expressLimit }</span>
                <span class="tag">{ shop.expressPrice === 0 ? '全免运费' : `基础运费¥${shop.expressPrice}` }</span>
              </div>
              <div class="vip">{ shop.desc }</div>
              <div class="search__products">
                { productList }
              </div>
            </div>
          </div>
        )
      })
      return (
        <div class="search__result">
          <header>
            <div class="iconfont icon-back" onClick={ () => { router.back() } }></div>
            <SearchInput v-model={ searchText.value } onKeyup={ () => search(searchText.value, false, () => searchShop(searchText.value)) } />
          </header>
          <div class="search__shops">
            { shopList }
          </div>
        </div>
      )
    }
  }
})
